import json
import time

from util.myredis import r
from views.base import BaseHandler
import tornado.websocket
import tornado.web

from db import db

conndict={}
class WebsockHandler(tornado.websocket.WebSocketHandler):
    # 跨域支持
    def check_origin(self, origin):
        return True
    #建立连接
    def open(self):
        #获取参数
        id = int(self.get_query_argument("id"))
        #存储链接
        conndict[id]=self
    #接收消息
    def on_message(self,mes):
        print(mes)

    def on_close(self):
        pass


class TTHandler(tornado.web.RequestHandler):
    def get(self):
            id = int(self.get_query_argument('id'))
            # wd = int(self.get_query_argument('wd'))
            # r.str_add("keyss", wd)
            while True:
                web = r.str_get('keyss')
                print(web)
                if web:
                    key = int(web.decode())
                    sql = "select * from web"
                    res = db.findAll(sql)
                    list = []
                    for i in res:
                        if i['min'] <=key<=i['max']:
                            status = 1
                            list.append({'id':i['id'],'name':i['name'],'min':i['min'],'max':i['max'],'status':status,'wendu':key})
                        else:
                            status = 0
                            list.append({'id':i['id'],'name':i['name'],'min':i['min'],'max':i['max'],'status':status,'wendu':key})
                    print("lst>>>>>",json.dumps(list))
                    time.sleep(3)
                    conndict[id].write_message(json.dumps(list))

class getweb(BaseHandler):
    def get(self):
        sql = "select * from web"
        res = db.findAll(sql)
        return self.finish({"code":200,"data":res})


clst = []
cdict={}
class Websock(tornado.websocket.WebSocketHandler):
    # 跨域支持
    def check_origin(self, origin):
        return True
    #建立连接
    def open(self):
        #获取参数
        id = str(self.get_query_argument("id"))
        username = str(self.get_query_argument("username"))
        #存储链接
        cdict[id]=self
        # 判断是否为用户，如果为用户加入userlist
        index = id.find("kefu")
        if index >= 0:
            # 判断是否为客服 如果为客服返回userlist
            self.write_message({"code":200,"userlist":clst,"mm":{}})
        else:
            # 判断是否为用户 如果为用户加入userlist
            clst.append({"id":id,"name":username})
            # 用户上线
            key = "levelmes" + str(id)
            mm = r.str_get(key)
            if mm:
                mm = mm.decode()
                self.write_message({"code": 200, "userlist": clst, "mm": mm})

    #接收消息
    def on_message(self,mes):
        mes = json.loads(mes)
        id = mes["id"]
        mm = mes["mm"]
        # 如果客服给用户发，判断用户是否在线，如果不在线将消息存入redis key：用户id + "levelmes",value:[
        if id in cdict:
            cdict[id].write_message({"code":200,"userlist":clst,"mm":mm})
        else:
            key = "levelmes" + str(id)
            # 用户不在存入redis
            r.str_add(key,mes)




    def on_close(self):
        pass
